<html lang="en-US">

<head>
    
<title>「连载五」基于 CA 的 TLS 证书认证 - 花落雨忧</title>

<meta property="og:title" content="「连载五」基于 CA 的 TLS 证书认证 - 花落雨忧">



    



    
    <meta property="description" content="在上一章节中，我们提出了一个问题。就是如何保证证书的可靠性和有效性？你如何确定你 Server、Client 的证书是对的呢？
[&amp;hellip;] 为了保证证书的可靠性和有效性，在这里可引入 CA 颁发的根证书的概念。其遵守 X.509 标准
[&amp;hellip;] 根证书（root certificate）是属于根证书颁发机构（CA）的公钥证书。我们可以通过验证 CA 的签名从而信任 CA ，任 &amp;hellip;">
    <meta property="og:description" content="在上一章节中，我们提出了一个问题。就是如何保证证书的可靠性和有效性？你如何确定你 Server、Client 的证书是对的呢？
[&amp;hellip;] 为了保证证书的可靠性和有效性，在这里可引入 CA 颁发的根证书的概念。其遵守 X.509 标准
[&amp;hellip;] 根证书（root certificate）是属于根证书颁发机构（CA）的公钥证书。我们可以通过验证 CA 的签名从而信任 CA ，任 &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.asia/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.asia/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.asia/js/jquery.min.js"></script>




<link href="https://www.lican.asia/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>

        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/posts/go/grpc/2018-10-08-ca-tls/">「连载五」基于 CA 的 TLS 证书认证</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2018/10/08</a>
                                            
                                            
                                            
                                            By 
                                            <a class="author" href="javascript:;">煎鱼</a></div>
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <h2 id="前言">前言</h2>
<p>在上一章节中，我们提出了一个问题。就是如何保证证书的可靠性和有效性？你如何确定你 Server、Client 的证书是对的呢？</p>
<h2 id="ca">CA</h2>
<p>为了保证证书的可靠性和有效性，在这里可引入 CA 颁发的根证书的概念。其遵守 X.509 标准</p>
<h3 id="根证书">根证书</h3>
<p>根证书（root certificate）是属于根证书颁发机构（CA）的公钥证书。我们可以通过验证 CA 的签名从而信任 CA ，任何人都可以得到 CA 的证书（含公钥），用以验证它所签发的证书（客户端、服务端）</p>
<p>它包含的文件如下：</p>
<ul>
<li>公钥</li>
<li>密钥</li>
</ul>
<h3 id="生成-key">生成 Key</h3>
<pre tabindex="0"><code>openssl genrsa -out ca.key 2048
</code></pre><h3 id="生成密钥">生成密钥</h3>
<pre tabindex="0"><code>openssl req -new -x509 -days 7200 -key ca.key -out ca.pem
</code></pre><h4 id="填写信息">填写信息</h4>
<pre tabindex="0"><code>Country Name (2 letter code) []:
State or Province Name (full name) []:
Locality Name (eg, city) []:
Organization Name (eg, company) []:
Organizational Unit Name (eg, section) []:
Common Name (eg, fully qualified host name) []:go-grpc-example
Email Address []:
</code></pre><h3 id="server">Server</h3>
<h4 id="生成-csr">生成 CSR</h4>
<pre tabindex="0"><code>openssl req -new -key server.key -out server.csr
</code></pre><h5 id="填写信息-1">填写信息</h5>
<pre tabindex="0"><code>Country Name (2 letter code) []:
State or Province Name (full name) []:
Locality Name (eg, city) []:
Organization Name (eg, company) []:
Organizational Unit Name (eg, section) []:
Common Name (eg, fully qualified host name) []:go-grpc-example
Email Address []:

Please enter the following &#39;extra&#39; attributes
to be sent with your certificate request
A challenge password []:
</code></pre><p>CSR 是 Cerificate Signing Request 的英文缩写，为证书请求文件。主要作用是 CA 会利用 CSR 文件进行签名使得攻击者无法伪装或篡改原有证书</p>
<h4 id="基于-ca-签发">基于 CA 签发</h4>
<pre tabindex="0"><code>openssl x509 -req -sha256 -CA ca.pem -CAkey ca.key -CAcreateserial -days 3650 -in server.csr -out server.pem
</code></pre><h3 id="client">Client</h3>
<h3 id="生成-key-1">生成 Key</h3>
<pre tabindex="0"><code>openssl ecparam -genkey -name secp384r1 -out client.key
</code></pre><h3 id="生成-csr-1">生成 CSR</h3>
<pre tabindex="0"><code>openssl req -new -key client.key -out client.csr
</code></pre><h4 id="基于-ca-签发-1">基于 CA 签发</h4>
<pre tabindex="0"><code>openssl x509 -req -sha256 -CA ca.pem -CAkey ca.key -CAcreateserial -days 3650 -in client.csr -out client.pem
</code></pre><h3 id="整理目录">整理目录</h3>
<p>至此我们生成了一堆文件，请按照以下目录结构存放：</p>
<pre tabindex="0"><code>$ tree conf 
conf
├── ca.key
├── ca.pem
├── ca.srl
├── client
│   ├── client.csr
│   ├── client.key
│   └── client.pem
└── server
    ├── server.csr
    ├── server.key
    └── server.pem
</code></pre><p>另外有一些文件是不应该出现在仓库内，应当保密或删除的。但为了真实演示所以保留着（敲黑板）</p>
<h2 id="grpc">gRPC</h2>
<p>接下来将正式开始针对 gRPC 进行编码，改造上一章节的代码。目标是基于 CA 进行 TLS 认证 🤫</p>
<h3 id="server-1">Server</h3>
<pre tabindex="0"><code>package main

import (
	&#34;context&#34;
	&#34;log&#34;
	&#34;net&#34;
	&#34;crypto/tls&#34;
	&#34;crypto/x509&#34;
	&#34;io/ioutil&#34;

	&#34;google.golang.org/grpc&#34;
	&#34;google.golang.org/grpc/credentials&#34;

	pb &#34;github.com/EDDYCJY/go-grpc-example/proto&#34;
)

...

const PORT = &#34;9001&#34;

func main() {
	cert, err := tls.LoadX509KeyPair(&#34;../../conf/server/server.pem&#34;, &#34;../../conf/server/server.key&#34;)
	if err != nil {
		log.Fatalf(&#34;tls.LoadX509KeyPair err: %v&#34;, err)
	}

	certPool := x509.NewCertPool()
	ca, err := ioutil.ReadFile(&#34;../../conf/ca.pem&#34;)
	if err != nil {
		log.Fatalf(&#34;ioutil.ReadFile err: %v&#34;, err)
	}

	if ok := certPool.AppendCertsFromPEM(ca); !ok {
		log.Fatalf(&#34;certPool.AppendCertsFromPEM err&#34;)
	}

	c := credentials.NewTLS(&amp;tls.Config{
		Certificates: []tls.Certificate{cert},
		ClientAuth:   tls.RequireAndVerifyClientCert,
		ClientCAs:    certPool,
	})

	server := grpc.NewServer(grpc.Creds(c))
	pb.RegisterSearchServiceServer(server, &amp;SearchService{})

	lis, err := net.Listen(&#34;tcp&#34;, &#34;:&#34;+PORT)
	if err != nil {
		log.Fatalf(&#34;net.Listen err: %v&#34;, err)
	}

	server.Serve(lis)
}
</code></pre><ul>
<li>tls.LoadX509KeyPair()：从证书相关文件中<strong>读取</strong>和<strong>解析</strong>信息，得到证书公钥、密钥对</li>
</ul>
<pre tabindex="0"><code>func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
	certPEMBlock, err := ioutil.ReadFile(certFile)
	if err != nil {
		return Certificate{}, err
	}
	keyPEMBlock, err := ioutil.ReadFile(keyFile)
	if err != nil {
		return Certificate{}, err
	}
	return X509KeyPair(certPEMBlock, keyPEMBlock)
}
</code></pre><ul>
<li>x509.NewCertPool()：创建一个新的、空的 CertPool</li>
<li>certPool.AppendCertsFromPEM()：尝试解析所传入的 PEM 编码的证书。如果解析成功会将其加到 CertPool 中，便于后面的使用</li>
<li>credentials.NewTLS：构建基于 TLS 的 TransportCredentials 选项</li>
<li>tls.Config：Config 结构用于配置 TLS 客户端或服务器</li>
</ul>
<p>在 Server，共使用了三个 Config 配置项：</p>
<p>（1）Certificates：设置证书链，允许包含一个或多个</p>
<p>（2）ClientAuth：要求必须校验客户端的证书。可以根据实际情况选用以下参数：</p>
<pre tabindex="0"><code>const (
	NoClientCert ClientAuthType = iota
	RequestClientCert
	RequireAnyClientCert
	VerifyClientCertIfGiven
	RequireAndVerifyClientCert
)
</code></pre><p>（3）ClientCAs：设置根证书的集合，校验方式使用 ClientAuth 中设定的模式</p>
<h3 id="client-1">Client</h3>
<pre tabindex="0"><code>package main

import (
	&#34;context&#34;
	&#34;crypto/tls&#34;
	&#34;crypto/x509&#34;
	&#34;io/ioutil&#34;
	&#34;log&#34;

	&#34;google.golang.org/grpc&#34;
	&#34;google.golang.org/grpc/credentials&#34;

	pb &#34;github.com/EDDYCJY/go-grpc-example/proto&#34;
)

const PORT = &#34;9001&#34;

func main() {
	cert, err := tls.LoadX509KeyPair(&#34;../../conf/client/client.pem&#34;, &#34;../../conf/client/client.key&#34;)
	if err != nil {
		log.Fatalf(&#34;tls.LoadX509KeyPair err: %v&#34;, err)
	}

	certPool := x509.NewCertPool()
	ca, err := ioutil.ReadFile(&#34;../../conf/ca.pem&#34;)
	if err != nil {
		log.Fatalf(&#34;ioutil.ReadFile err: %v&#34;, err)
	}

	if ok := certPool.AppendCertsFromPEM(ca); !ok {
		log.Fatalf(&#34;certPool.AppendCertsFromPEM err&#34;)
	}

	c := credentials.NewTLS(&amp;tls.Config{
		Certificates: []tls.Certificate{cert},
		ServerName:   &#34;go-grpc-example&#34;,
		RootCAs:      certPool,
	})

	conn, err := grpc.Dial(&#34;:&#34;+PORT, grpc.WithTransportCredentials(c))
	if err != nil {
		log.Fatalf(&#34;grpc.Dial err: %v&#34;, err)
	}
	defer conn.Close()

	client := pb.NewSearchServiceClient(conn)
	resp, err := client.Search(context.Background(), &amp;pb.SearchRequest{
		Request: &#34;gRPC&#34;,
	})
	if err != nil {
		log.Fatalf(&#34;client.Search err: %v&#34;, err)
	}

	log.Printf(&#34;resp: %s&#34;, resp.GetResponse())
}
</code></pre><p>在 Client 中绝大部分与 Server 一致，不同点的地方是，在 Client 请求 Server 端时，Client 端会使用根证书和 ServerName 去对 Server 端进行校验</p>
<p>简单流程大致如下：</p>
<ol>
<li>Client 通过请求得到 Server 端的证书</li>
<li>使用 CA 认证的根证书对 Server 端的证书进行可靠性、有效性等校验</li>
<li>校验 ServerName 是否可用、有效</li>
</ol>
<p>当然了，在设置了 <code>tls.RequireAndVerifyClientCert</code> 模式的情况下，Server 也会使用 CA 认证的根证书对 Client 端的证书进行可靠性、有效性等校验。也就是两边都会进行校验，极大的保证了安全性 👍</p>
<h3 id="验证">验证</h3>
<p>重新启动 server.go 和执行 client.go，查看响应结果是否正常</p>
<h2 id="总结">总结</h2>
<p>在本章节，我们使用 CA 颁发的根证书对客户端、服务端的证书进行了签发。进一步的提高了两者的通讯安全</p>
<p>这回是真的大功告成了！</p>
<h2 id="参考">参考</h2>
<h3 id="本系列示例代码">本系列示例代码</h3>
<ul>
<li><a href="https://github.com/EDDYCJY/go-grpc-example">go-grpc-example</a></li>
</ul>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc/2018-10-07-grpc-tls/">「连载四」TLS 证书认证</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc/2018-09-24-stream-client-server/">「连载三」gRPC Streaming, Client and Server</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc/2018-09-23-client-and-server/">「连载二」gRPC Client and Server</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc/2018-09-22-install/">「连载一」gRPC及相关介绍</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/pkg/2018-09-28-log/">log 标准库</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            <li>
                                                <a href="/tags/grpc" title="View all posts tagged match">grpc</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.asia/posts/posts/go/grpc/2018-10-07-grpc-tls/"
                                                    rel="prev">「连载四」TLS 证书认证</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.asia/posts/posts/go/grpc/2018-10-10-interceptor/">「连载六」Unary and Stream interceptor</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.asia/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    <section id="qrcode" class="widget widget_media_image">
        <h2 class="widget-title">微信公众号</h2>
        <img width="258" height="258"
            src="https://www.lican.asia/wechat/lican.png"
            class="image wp-image-5514  attachment-full size-full" alt=""
            style="max-width: 100%; height: auto;"
            sizes="(max-width: 258px) 100vw, 258px">
    </section>
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.asia All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>